var express = require('express');
var router = express.Router();
// 引入xss
var xss = require("xss");
//建立一个连接池
const {query, connection} = require("../config/mysqlpool");

function restdata(code, msg,data) {
    return {
        code: code,
        msg: msg,
        data:data
    }
}

//获取训练项目
router.get('/gettrains', function (req, res) {
    let uid = xss(req.query.user_id)
    query("select  train_name, train_name_id from train_names where user_id = ?", [uid], function (err, vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, err))
        } else {
            res.json(vals)
        }
    })
});
//添加动作
router.get('/addtrains', function (req, res) {
    let name = xss(req.query.train_name)
    let uid = xss(req.query.user_id)
    query("insert into `train_names` ( `train_name`, `user_id`) values (?,?)", [name, uid], function (err, vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, err))
        } else {
            res.json(restdata(200, "添加成功"))
        }
    })
});
//删除动作名
router.get('/removetrains', function (req, res) {
    let name = xss(req.query.train_name)
    let uid = xss(req.query.user_id)
    query("delete from `train_schedule`.`train_names` where `train_name`=? and `user_id`=? ", [name, uid], function (err, vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, err))
        } else {
            res.json(restdata(200, "删除成功"))
        }
    })
});

//添加训练记录
router.post('/add', function (req, res) {

    let user_id = xss(req.body.user_id)
    let random = Date.now().toString() + user_id.toString()
    let detailid = parseInt(random)
    console.log("当前ID是", detailid);
    let train_kind = xss(req.body.train_kind)
    let actionArr = req.body.actions
    // actionArr = JSON.parse(actionArr)
    console.log(actionArr)
    connection.getConnection(function (err, conn) {
        if (err) {
            console.log('CONNECT ERROR:', err.message);
            callback(err, null, null);
        } else {
            conn.beginTransaction(function (err) {
                if (err) {
                    throw err;
                }
                conn.query("insert into `train_schedule`.`train_record` ( `train_kind`, `user_id`, `train_detail`) values ( ?,?,?)", [train_kind, user_id, detailid], function (err, result) {

                    if (err) {
                        console.log("第一出错", err)
                        conn.rollback(function () {
                            throw err;
                        });
                    }
                    // console.log("第一ok",result)
                    let count = actionArr.length
                    console.log("count是", count)
                    let a = 0
                    for (let obj of actionArr) {
                        console.log("a是:", a)
                        console.log("obj是", obj)
                        let train_name_id = obj.train_name_id
                        let counts = obj.count
                        console.log("obj的train_name_id属性是:", train_name_id)
                        console.log("obj的counts属性是:", counts)
                        conn.query("insert into `train_schedule`.`train_detail` ( `train_name_id`, `counts`, `train_detail_id`) values ( ?, ?, ?)", [train_name_id, counts, detailid], function (err, result) {
                            if (err) {
                                console.log("第二出错", err)
                                conn.rollback(function () {
                                    throw err;
                                });
                            }
                            a++
                            // console.log("第二ok",result)
                            if (a === count) {
                                console.log("a===count")
                                conn.commit(function (err) {
                                    if (err) {
                                        conn.rollback(function () {
                                            throw err;
                                        });
                                    }
                                    console.log('success!');
                                    res.send(restdata(200, "添加成功"))
                                    conn.release();
                                });
                            }

                        });
                    }

                });
            });

        }
    });
});

//获取训练类型,参数uid
router.get('/gettrainkinds',function (req,res) {
    // var train_kind = xss(req.query.train_kind)
    let uid = xss(req.query.user_id)
    query('SELECT train_record.train_kind FROM train_record WHERE user_id=? GROUP BY train_kind',[uid],function (err,vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, "error"))
        } else {
            res.json(restdata(200, 'success',vals))
        }
    })
})
//根据训练类型获得训练日期，参数：user_id，train_kind
router.get('/gettraindate',function (req,res) {
    let train_kind = xss(req.query.train_kind)
    let uid = xss(req.query.user_id)
    query('SELECT train_record.cteate_time, \n' +
        '\ttrain_record.train_detail\n' +
        'FROM train_record\n' +
        'WHERE user_id=?  and train_kind=?',[uid,train_kind],function (err,vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, "error"))
        } else {
            // for (let obj of vals){
            //     obj.cteate_time
            // }
            res.json(restdata(200, 'success',vals))
        }
    })
})
//背部训练所有动作的柱形图数据对比
router.get('/getcontrast',function (req,res) {
    let train_kind = xss(req.query.train_kind)
    let uid = xss(req.query.user_id)
    query('SELECT train_detail \n' +
        'FROM train_record\n' +
        'WHERE user_id=?  and train_kind=?',[uid,train_kind],function (err,vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, "error",err))
        } else {
            let valsa = vals.map(item=>item.train_detail)
            let count  = valsa.length
            let results = []
            let a = 0
            for (let b of valsa ){
                query('select train_name_id,counts from train_detail where train_detail_id = ?',[b],function (err,vals) {
                    // console.log("查到的结果是",vals)
                    if (err){
                        res.json(restdata(400, "error",err))
                    }
                    for (let i = 0; i < vals.length; i++) {
                        let obj = vals[i];
                        results.push(obj)
                    }
                    a++
                    // console.log("a是",a)
                    if (a === count){

                        console.log("最终是:",results)
                        res.json(restdata(200, 'success',results))
                    }
                })
            }
        }
    })
})
//根据train_name_id获得实际名字
router.get('/gettrainnamebyid',function (req,res) {
    let train_name_id = xss(req.query.train_name_id)
    query('select train_name from train_names where train_name_id = ?',[train_name_id],function (err,vals) {
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400, "error"))
        } else {
            if (vals.length == 0){
                res.json(restdata(200, 'success',[{train_name:"未知"}]))
            }else{
                res.json(restdata(200, 'success',vals))
            }

        }
    })
})
module.exports = router;
